//扣子访问
const express = require('express');
const router = express.Router();
const axios = require('axios');
const { v4: uuidv4 } = require('uuid');
const jwt = require('jsonwebtoken');
const fs = require('fs');

/* GET home page. */
router.post('/', async (req, res, next) => {

    try{
        const {id,phone,userText} = req.body
        //校验参数是否合法
        if (!phone  || !userText) {
            res.status(400).json({
                code: 400,
                msg: '缺少必要的参数',
                data:''
            })
            return
        }

        //获取访问令牌
        const token = await getToken()

        //发起对话
        const dialogueRequest = await initiateDialogue(phone, userText, token)

        //查询状态
       // const pollingResult = await pollUntilCompletedWithPromise(dialogueRequest.data.id, dialogueRequest.data.conversation_id, token)

        //查看对话消息详细
        //const result = await getResult(dialogueRequest.data.id, dialogueRequest.data.conversation_id,token)

        //返回的数据
        res.json({
            code: 200,
            msg: '账单分析成功',
            data: {
                result:dialogueRequest
            }
        });
    }
    catch (e) {
        res.status(401).json({
            msg: 401,
            message: '访问异常' + e.message
        });
    }

});

//获取访问令牌
async function getToken() {
    try {
        //生成时间
        const now = new Date();
        const timestamp = now.getTime();
        //生成随机数
        const uuid = uuidv4()
        const Header = {alg: 'RS256', typ: 'JWT', kid: 'yZOJs2AjECWd7dVe1SsBQC_a3DlbYbwVMxUEdiUij_0'}
        const Payload = {iss: '1175888414578', aud: 'api.coze.cn', iat: timestamp, exp: timestamp + 60000 * 10, jti: uuid}
        const encodedHeader = JSON.stringify(Header).toString('base64url')
        const encodedPayload = JSON.stringify(Payload).toString('base64url')
        // 读取私钥
        const privateKey = fs.readFileSync('config/private_key.pem', 'utf8');
        //签名JWT
        const JWT = jwt.sign({...Payload}, privateKey, {
            algorithm: 'RS256',
            header: Header
        })

        //获取访问令牌
         const result = await axios.post('https://api.coze.cn/api/permission/oauth2/token', {
            duration_seconds: 900,
            grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer'
        }, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${JWT}`
            }
        })

        //返回结果
        return result.data.access_token
    }
    catch (e) {
        throw e
    }

}

//发起对话
async function initiateDialogue(phone,userText,token){

    try{
        //发起对话
        const dialogueRequest = await axios.post(' https://api.coze.cn/v3/chat',
            {
                //botID
                bot_id:'7399972797323395099',
                //用户ID
                user_id:phone,
                //发起对话的内容
                additional_messages:[
                    {
                        //发送这条消息的实体
                        role:'user',
                        //消息的内容
                        content:userText,
                        //消息的类型
                        content_type:'text',
                    }
                ],
                stream:true

            },
            {
                headers:{
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                }
            }
        )
        //返回的流
        const result = dialogueRequest.data
        const events = result.split('\n\n').filter(Boolean); // 使用filter去除空字符串
        const parsedEvents = events.map(event => {
            const [eventType, eventData] = event.split('\ndata:');
            return {
                eventType: eventType.trim(),
                eventData: JSON.parse(eventData.trim())
            };
        })
        const completedMessages = parsedEvents.filter(event => event.eventType === 'event:conversation.message.completed' && event.eventData.type === 'answer');

        //返回最终结果
        return completedMessages
    }
    catch (e) {
        throw e
    }


}


module.exports = router;